package com.ke.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ke.reggie.common.R;
import com.ke.reggie.entity.User;
import com.ke.reggie.service.UserService;
import com.ke.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: reggie_take_out
 * @BelongsPackage: com.ke.reggie.controller
 * @Author: ke_huifeng
 * @CreateTime: 2022-10-06  20:42
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){

        String phone = user.getPhone();
        if(!StringUtils.isEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info(code);
//            session.setAttribute(phone, code);
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");     //使用smpt的邮件传输协议
            props.setProperty("mail.smtp.host", "smtp.qq.com");       //主机地址
            props.setProperty("mail.smtp.auth", "true");      //授权通过

            Session session1 = Session.getInstance(props);     //通过我们的这些配置，得到一个会话程序

            try {

                MimeMessage message = new MimeMessage(session1);
                message.setFrom(new InternetAddress("2210357520@qq.com"));     //设置发件人
                message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("2308134701@qq.com","用户","utf-8"));      //设置收件人
                message.setSubject("演示发邮件验证码网","utf-8");      //设置主题
                message.setSentDate(new Date());

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                String str = "<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body><p style='font-size: 20px;font-weight:bold;'>尊敬的："+"2308134701@qq.com"+"，您好！</p>"
                        + "<p style='text-indent:2em; font-size: 20px;'>欢迎注册xxx网，您本次的注册码是 "
                        + "<span style='font-size:30px;font-weight:bold;color:red'>" + code + "</span>，1分钟之内有效，请尽快使用！</p>"
                        + "<p style='text-align:right; padding-right: 20px;'"
                        + "<a href='http://www.hyycinfo.com' style='font-size: 18px'>xxxx有限公司</a></p>"
                        + "<span style='font-size: 18px; float:right; margin-right: 60px;'>" + sdf.format(new Date()) + "</span></body></html>";

                Multipart mul=new MimeMultipart();  //新建一个MimeMultipart对象来存放多个BodyPart对象
                BodyPart mdp=new MimeBodyPart();  //新建一个存放信件内容的BodyPart对象
                mdp.setContent(str, "text/html;charset=utf-8");
                mul.addBodyPart(mdp);  //将含有信件内容的BodyPart加入到MimeMultipart对象中
                message.setContent(mul); //把mul作为消息内容


                message.saveChanges();

                //创建一个传输对象
                Transport transport=session1.getTransport("smtp");

                //建立与服务器的链接  465端口是 SSL传输
                transport.connect("smtp.qq.com", 587, "2210357520@qq.com", "bpwjykjkweiqeaja");

                //发送邮件
                transport.sendMessage(message,message.getAllRecipients());

                //关闭邮件传输
                transport.close();

            } catch (AddressException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
            return  R.success("手机验证码短信发送成功");
        }
        return  R.error("短信发送失败");

    }

    @PostMapping("/login")
    private R<User> login(@RequestBody Map map, HttpSession session){

        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

//        String codeInSession = session.getAttribute(phone).toString();
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);
        if (codeInSession != null && codeInSession.equals(code)){
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getPhone, phone);

            User user = userService.getOne(userLambdaQueryWrapper);
            if(user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登录失败");
    }
}
